﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace PlaceHR.Processor.Processor.Salary.Steps
{
    class BonusSalaryStepCalculator : StepCalculatorBase<SalaryProcessorContext, EmployeeSalary>
    {
        public override void Calculate(SalaryProcessorContext salaryProcessorContext, EmployeeSalary employeeSalary)
        {
            int bonusMonth = 12;
            if (ConfigurationManager.AppSettings["BonusMonth"] != null)
            {
                bonusMonth = Convert.ToInt32(ConfigurationManager.AppSettings["BonusMonth"]);
            }

            if (bonusMonth != salaryProcessorContext.CurrentEngine.Month)
            {
                return;
            }

            var monthUnpaidLeave = salaryProcessorContext.CurrentEmployee.EmployeeVacation.Where(p => !p.IsDeleted
                && p.VacationTypeCode.Equals("UPL", StringComparison.OrdinalIgnoreCase)
                && !p.Status.Equals("Denied", StringComparison.OrdinalIgnoreCase)
                && p.FromTime.HasValue
                && p.FromTime.Value.Year == salaryProcessorContext.CurrentEngine.Year).ToList();
            
            decimal vacationHours = 0;
            if (monthUnpaidLeave != null && monthUnpaidLeave.Count > 0)
            {
                foreach (var item in monthUnpaidLeave)
                {
                    vacationHours = vacationHours + item.Length.GetValueOrDefault();
                }
            }

            if (vacationHours > 0)
            {
                var totalSalary = (employeeSalary.BasicSalary ?? 0)
                                    + (employeeSalary.PositionSalary ?? 0)
                                    + (employeeSalary.Others ?? 0);
                employeeSalary.Bonus = (totalSalary / salaryProcessorContext.WorkingDaysPerMonth) * (10 - vacationHours / salaryProcessorContext.WorkingHoursPerDay);
                employeeSalary.Bonus = employeeSalary.Bonus >= 0 ? employeeSalary.Bonus : 0;
            }

        }

    }
}
